package com.adou.shiro.util;

import com.adou.common.util.IConfig;
import com.adou.common.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

public class ShiroFilterUtils {

    private static final Logger logger = LoggerFactory.getLogger(ShiroFilterUtils.class);
    /**
     * 是否是Ajax请求(跨域X-Requested-With失效，客户端做请求信息头处理的解决方式见CORSFilter预请求)
     *
     * @param request
     * @return
     */
    public static boolean isAjax(ServletRequest request) {
        String xrequest=((HttpServletRequest) request).getHeader("X-Requested-With");
        return "XMLHttpRequest".equalsIgnoreCase(xrequest) || "io.dcloud.HBuilder".equalsIgnoreCase(xrequest);
    }

    /**
     * 是否是Ajax请求(跨域X-Requested-With失效，客户端不做请求信息头处理的解决方式)
     *
     * @param request
     * @param response
     * @return
     */
    public static boolean isAjax(ServletRequest request,ServletResponse response) {
        String xrequest=((HttpServletRequest) request).getHeader("X-Requested-With");
        String host=((HttpServletRequest) request).getHeader("Host");
        String origin=((HttpServletRequest) request).getHeader("Origin");
        String alloworigin=((HttpServletResponse) response).getHeader("Access-Control-Allow-Origin");
        return "XMLHttpRequest".equalsIgnoreCase(xrequest) || "io.dcloud.HBuilder".equalsIgnoreCase(xrequest) || ((alloworigin.equals("*") || alloworigin.indexOf(origin)!=-1) && !host.equals(origin));
    }

    /**
     * 是否是移动端
     *
     * @param ua=request.getHeader("User-Agent")
     * @return
     */
    public static boolean checkAgentIsMobile(String ua) {
        String[] agent = {IConfig.get("agent")};
        boolean flag = false;
        if (!ua.contains("Windows NT") || (ua.contains("Windows NT") && ua.contains("compatible; MSIE 9.0;"))) {
            // 排除 苹果桌面系统
            if (!ua.contains("Windows NT") && !ua.contains("Macintosh")) {
                for (String item : agent) {
                    if (ua.contains(item)) {
                        flag = true;
                        break;
                    }
                }
            }
        }
        return flag;
    }

    /**
     * response 输出JSON
     *
     * @param response
     * @param resultMap
     */
    public static void out(ServletResponse response, Map<String, String> resultMap) {
        PrintWriter out = null;
        try {
            response.setContentType("text/html;charset=utf-8");
            out = response.getWriter();
            out.println(JsonUtil.collectToString(resultMap));
        } catch (Exception e) {
            logger.error("输出JSON报错。");
        } finally {
            if (null != out) {
                out.flush();
                out.close();
            }
        }
    }
}
